//
//  StatusDAL.swift
//  glzbowei
//
//  Created by 高伦展 on 2018/4/11.
//  Copyright © 2018年 glz. All rights reserved.
//

import Foundation

private let maxCacheDateTime:TimeInterval = 60 //7 * 24 * 60 * 60

//数据访问层 - 目标：专门负责处理本地 SQLite 和 网络数据
class StatusDAL{
    
    /**
     1.清理缓存工作，千万不要交给用户使用。
     2.一定要定期清理数据库的缓存，原因：
     - SQLite 的数据库，随着数据的增加，会不断的变大
     - 但是，如果删除了数据，数据库不会变小！sqlite 认为，既然数据库会涨到这么大，留出空间，准备下一次涨到这么大
        - SQLite不会再额外分配磁盘空间
     - 一般不会把 图片/音频/视频 放在数据库中，不便于检索，占用磁盘空间很大
     */
    
    //清理‘早于过期日期’的缓存数据
    class func clearDataCache(){
        
        //准备时间
        let date = Date(timeIntervalSinceNow: -maxCacheDateTime)
        
        let df = DateFormatter()
        
        df.locale = Locale(identifier: "en")
        
        df.dateFormat = "yyyy-MM-dd HH:mm:ss"
        
        let dateStr = df.string(from: date)
        
        let sql = "delete from t_status where createtime < ?"
        
        SQLiteManager.shareManager.queue.inDatabase { (db) in
            if (db?.executeUpdate(sql: sql, dateStr as AnyObject))!{
                
            }
        }
    }
    
    //加载微博数据
    class func loadStatus(since_id:Int,max_id:Int,finished:@escaping (_ array:[[String:AnyObject]]?)->()) {
        
        //1.检查本地是否存在缓存数据
        let array = checkCacheData(since_id: since_id, max_id: max_id)
        
        if (array?.count)! > 0{
            finished(array!)
            return 
        }
        //2.如果有，返回缓存数据
        NetworkTools.sharedTools.loadStatus(since_id: since_id,max_id: max_id) { (result, error) in
            if error != nil {
                print("错误了")
                
                finished(nil)
                return
            }
            
            guard let array = result?["statuses"] as? [[String:AnyObject]] else
            {
                print("数据格式出错")
                finished(nil)
                return
            }
            
            StatusDAL.saveCacheData(array: array)
            
            finished(array)
        }
        //3.如果没有，加载网络数据
        
        //4.将网络返回的数据，保存在本地数据库，以便后续使用
        
        //5.返回网络数据
        
    }
    
    class func checkCacheData(since_id:Int,max_id:Int) -> [[String:AnyObject]]?{
        guard let userId = UserAccountViewModel.sharedUserAccount.account?.uid else{
            print("用户没登录")
            return nil
        }
        
        var sql = "select statusId,status,userId from t_status \n"
        sql += "where userId = \(userId) \n"
        
        if since_id > 0{
            sql += " and statusId > \(since_id) \n"
        } else if max_id > 0{
            sql += " and statusId < \(max_id) \n"
        }
        
        sql += "order by statusId desc limit 20;"
        
        print("sql语句："+sql)
        
        let array = SQLiteManager.shareManager.execRecordSet(sql: sql)
        
        //3.遍历数组
        var arrayM = [[String:AnyObject]]()
        for dict in array{
            let jsonData = dict["status"] as! Data
            
            let result = try! JSONSerialization.jsonObject(with: jsonData, options: [])
      
            arrayM.append(result as! [String : AnyObject])
        }
        
        return arrayM
    }
    
    class func saveCacheData(array:[[String:AnyObject]]){
       
        guard let userId = UserAccountViewModel.sharedUserAccount.account?.uid else{
            print("用户没登录")
            return
        }
        
        let sql = "insert or replace into t_status(statusId,status,userId) values(?,?,?)"
        
        SQLiteManager.shareManager.queue.inTransaction { (db, rollback) in
            for dict in array{
                let statusId = dict["id"] as! Int
                
                let json = try! JSONSerialization.data(withJSONObject: dict, options: [])
                
                if !(db?.executeUpdate(sql: sql, statusId as AnyObject,json as AnyObject,userId as AnyObject))!{
                    rollback?.pointee = true
                    break
                }
            }
        }
        
       
    }
}
